<?php

  class CategoriesHelper {

    private $items;

    public function __construct($items) {
      $this->items = $items;
    }

    public function htmlList() {
      return $this->htmlFromArray($this->itemArray());
    }
	
	public function jsonList() {
		return $this->jsonFromArray($this->itemArray());
	}
	public function jsonList2() {
		$category = Category::find(1);
		return '[{"title":"/", "key":"1", "expanded": true, "folder": true, "children": ['.HomeController::jsonList2($category).'] } ] ';
	}
	
    private function itemArray() {
      $result = array();
      foreach($this->items as $item) {
        if ($item->parent_id == 0) {
          $result[$item->name] = $this->itemWithChildren($item);
        }
      }
      return $result;
    }

    private function childrenOf($item) {
      $result = array();
      foreach($this->items as $i) {
        if ($i->parent_id == $item->id) {
          $result[] = $i;
        }
      }
      return $result;
    }

    private function itemWithChildren($item) {
      $result = array();
      $children = $this->childrenOf($item);
      foreach ($children as $child) {
        $result[$child->name] = $this->itemWithChildren($child);
      }
      return $result;
    }
	
    private function htmlFromArray($array) {
      $html = '';
      foreach($array as $k => $v) {
        $html .= "<ul>";
        $html .= "<li>".$k;
        if(count($v) > 0) {
          $html .= $this->htmlFromArray($v);
        }
		$html .= "</li>";
        $html .= "</ul>";
      }
      return $html;
    }

    private function jsonFromArray($array) {
      $html = '';
      foreach($array as $k => $v) {
        $html .= '{';
        $html .= '"title":"'.$k.'", "expanded": true, "folder": true';
				
        if(count($v) > 0) {
			$html .= ', "children": [';
			$html .= $this->jsonFromArray($v);
			$html .= ']} ,';
        } else {
			$html .= '} ,';
		}
      }	  
      return substr($html, 0, -1);
    }	
  }
  
  private function jsonList2($category) {
	  $html = '';
      foreach($category->children as $children) {
        $html .= '{';
        $html .= '"title":"'.$children->name.'", "key":"'.$children->id.'", "expanded": true, "folder": true';
				
        if(count($children->children) > 0) {
			$html .= ', "children": [';
			$html .= HomeController::jsonList2($children);
			$html .= ']} ,';
        } else {
			$html .= '} ,';
		}
      }	  
      return substr($html, 0, -1);
    }